<?php
namespace src;
use classlib\input;
use src\logic\Cadmin;
use classlib\core as C;
use classlib\core\controller;
class Cevent extends controller {
	public function main() {
		$view  = C\view::inst('extjs');
		Cadmin::chkaccess($view);
		$lang  = C\lang::inst('adm');
		$dlang = C\lang::inst('dd');
		$userid= (int)input::get_post('userid');
		$user  = '';
		if ($userid > 0) {
			$user = self::__user($userid);
		}
		$sdate = input::get_post('sdate');
		$edate = input::get_post('edate');
		$status= input::get_post('status');
		$view->assign('user', $user);
		$view->assign('userid', $userid);
		$view->assign('lstatus', $status);
		$view->assign('sdate', trim($sdate));
		$view->assign('edate', trim($edate));
		$view->assign('yes2no', $dlang->get('sh0007'));
		$view->assign('status', $dlang->get('et_status'));
		$view->assign('across', $dlang->get('et_across'));
		$view->assign('ischeck', $dlang->get('et_ischeck'));
		$view->assign_by_ref('title', Cadmin::$name);
		$view->display('live/event.ext.js');
	}
	
	/**
	 * @desc    审核直播主播直播场次资料信息
	 * @doc     审核直播
	 * @access  需要授权 
	 */
	public function dosave() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		$data   = array('chktime'=>C\config::$nowtime, 'ischeck'=>1);
		$filter = new \classlib\validator\auditor();
		$lang   = C\lang::inst('adm');
		$filter->lang($lang);
		try {
			$id = $filter->reset('id')->numeric()->min(1)->run();
			$data['status']    = $filter->reset('status')->numeric()->run();
			$data['wastetime'] = $filter->reset('wastetime')->numeric()->min(0)->run();
			$data['notes']     = $filter->reset('remarks')->required()->maxlen(255)->run();
			$data['operator']  = Cadmin::operator();
		} catch (\classlib\validator\AuditorException $e) {
			$view->assign_error($e->getField(), $e->getMessage());
		} catch (\Exception $e) {
			$view->assign_error($e->getCode(), $e->getMessage());
		}
		$orm    = C\model::load('pro.pl.event');
		$event  = $orm->get_one($id);
		if (!$event || ($event['lasttime'] - $event['aritime']) < $data['wastetime']) {
			$view->assign_error(40002, $lang->common(40002));
		}
		$data['notes'] = $event['notes'].'['.$data['notes'].']';
		$orm->save($id, $data);
		Cadmin::log2db('event_dosave:'.$id.C\view::inst('xml')->array2xml($data));
		$view->display();
	}
	
	/**
	 * @desc    批量审核直播场次
	 * @doc     审核记录
	 * @access  需要授权
	 */
	public function docheck() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		$data   = array('chktime'=>C\config::$nowtime, 'ischeck'=>1);
		$filter = new \classlib\validator\auditor();
		$lang   = C\lang::inst('adm');
		$filter->lang($lang);
		try {
			$data['status']    = $filter->reset('status')->numeric()->run();
			$data['notes']     = $filter->reset('notes')->required()->maxlen(63)->run();
			$data['operator']  = Cadmin::operator();
		} catch (\classlib\validator\AuditorException $e) {
			$view->assign_error($e->getField(), $e->getMessage());
		} catch (\Exception $e) {
			$view->assign_error($e->getCode(), $e->getMessage());
		}
		$orm    = C\model::load('pro.pl.event');
		$ids    = \classlib\validator\auditor::intstr2arr('ids');
		foreach ($ids as $id) {
			$event = $orm->get_one($id);
			if (!$event || $event['ischeck'] != 0) {
				continue;//已经审核过的不需要再次审核
			}
			($event['notes']) && ($data['notes'] .= $event['notes']); 
			$orm->save($id, $data);
		}
		Cadmin::log2db('event_check:'.implode(',', $ids).C\view::inst('xml')->array2xml($data));
		$view->display();
	}
	
	/**
	 * 获取直播场次资料列表
	 */
	public function dolist($return=false) {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		list($start, $limit, $sort) = Cadmin::offset();
		$where  = self::__where();
		$orm    = C\model::load('pro.pl.event');
		$total  = $orm->get_total($where);
		$list   = array();
		if ($total) {
			$list = self::__list($orm, $where, $start, $limit, $sort);
		}
		$view->assign_by_ref('total', $total);
		$view->assign_by_ref('dataset', $list);
		$view->display();
	}
	
	/**
	 * 获取执行条件的where语法
	 * @return array
	 */
	private function __where() {
		$where  = array();
		$userid = input::get_post('userid');
		if (is_numeric($userid) && $userid > 0) {
			$where[] = array('userid', $userid);
		}
		$tagid  = input::get_post('tagid');
		if (is_numeric($tagid)) {
			$where['tagid'] = $tagid;
		}
		$status = input::get_post('status');
		is_numeric($status) && ($where['status'] = $status);
		$ischeck= input::get_post('ischeck');
		is_numeric($ischeck) && ($where['ischeck'] = $ischeck);
		$sdate  = input::get_post('sdate');
		if ($sdate) {
			$where[] = array('offtime', strtotime($sdate), \classlib\orm::OP_GT);
		}
		$edate  = input::get_post('edate');
		if ($edate) {
			$where[] = array('offtime', strtotime($edate), \classlib\orm::OP_LT);
		}
		$lttime = input::get_post('lttime');
		if (is_numeric($lttime) && $lttime > 0) {
			$where[] = array('lasttime - aritime', $lttime, \classlib\orm::OP_LE);
		}
		$gttime = input::get_post('gttime');
		if (is_numeric($gttime) && $gttime > 0) {
			$where[] = array('lasttime - aritime', $gttime, \classlib\orm::OP_GE);
		}
		return $where;
	}
	
	private function __list($orm, $where, $start, $limit, $sort) {
		$state  = $orm->get_item($where, 'sum(lasttime - aritime) as livetime, sum(wastetime) as invalidtime');
		$list   = $orm->get_list($start, $limit, $where, '*', $sort);
		$torm   = C\model::load('pro.inc.tags');
		$stars  = C\model::load('pro.inc.star')
			->get_mapper(0, -1, null, 'id as `key`,name as val');
		$sorm   = C\model::load('pro.pl.studio');
		foreach ($list as &$item) {
			$item['slivetime']   = $item['lasttime'] - $item['aritime'];
			$item['svalidtime']  = $item['lasttime'] - $item['aritime'] - $item['wastetime'];
			$item['livetime']    = Cadmin::__format_times($item['slivetime']);
			$item['longtime']    = sprintf('%s[%d]', $item['livetime'], $item['slivetime']);
			$item['invalidtime'] = Cadmin::__format_times($item['wastetime']);
			$item['validtime']   = Cadmin::__format_times($item['svalidtime']);
			$item['stime']    = date('Y-m-d H:i', $item['stime']);
			$item['aritime']  = date('Y-m-d H:i', $item['aritime']);
			$item['lasttime'] = date('Y-m-d H:i', $item['lasttime']);
			$item['chktime']  = ($item['chktime'] > 0)? date('Y-m-d H:i', $item['chktime']):'';
			$item['offtime']  = ($item['offtime'] > 0)? date('Y-m-d H:i', $item['offtime']):'';
			$item['tag']      = '';
			if ($item['tagid'] > 0) {
				$tag = $torm->get_one($item['tagid']);
				$item['tag']  = empty($tag)? '':$tag['name'];
			}
			$item['starlv']   = isset($stars[$item['startlv']])? $stars[$item['startlv']]:'未知[UnKonw]';
			$studio = $sorm->get_one($item['studioid']);
			$item['user']  	  = self::__user($item['userid']);
			$item['link']  	  = C\router::get_url('live', $studio['studiono']);
			$item['profile']  = C\router::get_url('profile', $studio['studiono']);
		}
		$list[] = array('user'=>'合计[statistics]','livetime'=>Cadmin::__format_times($state['livetime']),
				'invalidtime'=>Cadmin::__format_times($state['invalidtime']),
				'validtime'=>Cadmin::__format_times($state['livetime']-$state['invalidtime']));
		return $list;
	}
	
	public function doexport() {
		$view   = C\view::inst('cvs');
		Cadmin::chkaccess($view);
		$header = array('id'=>'直播场次[ID]', 'user'=>'主播[Anchor]', 'title'=>'标题[Title]', 'tag'=>'分类[Tag]',
			'aritime'=>'开播时间[StartTime]', 'lasttime'=>'心跳时间[NotifyTime]', 'offtime'=>'心跳时间[NotifyTime]',
			'offtime'=>'结束时间[EndTime]', 'slivetime'=>'直播时长/s[LiveTime]', 'svalidtime'=>'有效时间/s[ValidTime]',
			'wastetime'=>'无效时间/s[InvalidTime]', 'starlv'=>'主播等级[StarLv]', 'status'=>'状态[Status]',
			'ischeck'=>'审核状态[IsCheck]', 'operator'=>'审核者[Operator]', 'chktime'=>'审核时间[CheckTime]', 'notes'=>'审核日志'
		);
		$orm    = C\model::load('pro.pl.event');
		$where  = self::__where();
		$list   = self::__list($orm, $where, 0, -1, null);
		$view->assign_by_ref('data', $list);
		$view->assign_by_ref('header', $header);
		$view->display();
	}
	
	//获取用户的资料信息
	private static function __user($userid) {
		static $users = array();
		if (!isset($users[$userid])) {
			$orm  = C\model::load('pro.pl.userinfo');
			$user = $orm->get_one($userid);
			$users[$userid] = empty($user)? '':$user['nickname'].'['.$user['email'].']';
		}
		return $users[$userid];
	}
}